#!/usr/bin/env jruby
# -*- coding: us-ascii -*-
# Elizabeth Wiethoff 2008

require 'java'

########################################

module FileDialogs
  include_class 'javax.swing.JFileChooser'
  include_class 'javax.swing.JOptionPane'
  
  class CSVFileFilter < javax.swing.filechooser.FileFilter
    # accept's arg is supposed to be a java.io.File.
    # But sometimes the calling thread is flaky, at least on Mac.
    # Using an exception block in the method usually helps.
    # Also, sometimes accept seems to expect 2 args, though the
    # API only indicates 1.
    def accept(file, *ignore)
      begin
        return true if file.isDirectory
        file.to_s =~ /\.(csv|txt)$/i ? true : false
      rescue
        true  # might as well let everything through
      end
    end
    
    def getDescription
      'CSV & TXT files'
    end
  end
  
  
  def FileDialogs.confirmOpenLargeGroup(gsz)
    title = 'Open All Files in Group'
    msg1 = "The selected group contains #{gsz} files."
    msg2 = "Do you want to open all #{gsz} files?"
    result = JOptionPane.showConfirmDialog(nil,
      [msg1, msg2].to_java, title, 
      JOptionPane::YES_NO_OPTION, JOptionPane::WARNING_MESSAGE)
    return result == JOptionPane::YES_OPTION
  end
  
  def FileDialogs.confirmTossFile(path)
    title = 'Toss File'
    msg = "Toss #{path}?"
    result = JOptionPane.showConfirmDialog(nil,
      msg, title, 
      JOptionPane::YES_NO_OPTION, JOptionPane::QUESTION_MESSAGE)
    return result == JOptionPane::YES_OPTION
  end
  
  def FileDialogs.inputRenameFile(fname)
    title = 'Rename File'
    msg = "Rename #{fname} to:"
    result = JOptionPane.showInputDialog(nil, 
      msg, title, JOptionPane::QUESTION_MESSAGE)
    if result  # is a string
      return [true, result] unless result.strip.empty?
    end
    return [false, nil]
  end
  
  def FileDialogs.chooseExportFile(path)
    dir, fname = File.split(path)  # dangerous with spaces?
    p dir, fname if $DEBUG
    chooser = JFileChooser.new(dir)
    chooser.setDialogTitle('Export Table as')
    chooser.setFileFilter(CSVFileFilter.new)
    chooser.setSelectedFile(java.io.File.new(fname))
    result = chooser.showDialog(nil, 'OK')  # prefer to showSaveDialog
    if result == JFileChooser::APPROVE_OPTION
      path = chooser.getSelectedFile.getPath
      return [true, path] unless path.empty?
    end
    return [false, nil]
  end
end
